package test.serverframe.armc.server.manager.service.exec;

import com.alibaba.fastjson.JSON;

import test.serverframe.armc.server.manager.service.exec.dag.Dag;
import test.serverframe.armc.server.manager.service.exec.dag.DagNode;
import test.serverframe.armc.server.manager.service.exec.dag.NodeInfo;
import test.serverframe.armc.server.manager.service.exec.model.TaskDagNode;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * XXXX
 *
 * @author LiuChunfu
 * @date 2019.01.19
 */
public abstract class BaseExecutor implements Runnable {

    public static Executor ThreadPool = Executors.newFixedThreadPool(30);

    /**
     * 创建图形节点
     *
     * @param id
     * @return
     */
    private DagNode create(String id) {
        return new TaskDagNode(id);
    }

    /**
     * 处理任务
     *
     * @param node
     */
    private void handle(DagNode node) {
    	Runnable run = getNodeExecutor(node);
    	if (run != null) {
    		ThreadPool.execute(run);
    	}
    }

    /**
     * 获取节点
     *
     * @return
     */
    public abstract List<NodeInfo> getNodeInfo();

    /**
     * 获取节点执行器，即BaseExecutor抽象类的实现
     *
     * @return
     */
    public abstract Runnable getNodeExecutor(DagNode node);

    @Override
    public void run() {
        //创建dag图形
        Dag dag = new Dag();
        dag.setNodeCreator(this::create);
        dag.setHandlerOnNodeActivated(this::handle);
        List<NodeInfo> nodeInfo = getNodeInfo();
        setNodeListSize(nodeInfo.size());
        dag.createDag(nodeInfo);
        dag.start();
    }

    protected List<String> convert2List(String parentIds) {
        return JSON.parseArray(parentIds, String.class);
    }

    private int nodeListSize = 0;

	public int getNodeListSize() {
		return nodeListSize;
	}

	public void setNodeListSize(int nodeListSize) {
		this.nodeListSize = nodeListSize;
	}
    
    
}